//
//  OpenSDK_DataManager.m
//  
//
//  Created by wyht－ios－dev on 16/2/24.
//
//

#import "OpenSDK_DataManager.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_LocalRecord.h"
#import <Y2Common/Y2Common.h>

@implementation OpenSDK_DataManager

static OpenSDK_DataManager *instance = nil;

+(instancetype) getInstance
{
    if(instance==nil)
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[self alloc] init];
            instance.supportSDKs = [[NSDictionary alloc] init];
            instance.supportSDKServerNames = [[NSDictionary alloc] init];
        });
    }
    return instance;
}

+(NSString *) getSMSUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/v2/open/oauth/sms"];
}

+(NSString *) getResetPasswordUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/password/reset"];
}

+(NSString *) getUserRealNameUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/v2/open/oauth/realname"];
}

+(NSString*) getInitUrl
{
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/v2/open/sdk/init"];
}

+(NSString *) getBindActiveCodeUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/activation_code_status"];
}

+(NSString *) getQueryActiveStatusUrl {
    return [[[[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/activation_code_status"] stringByAppendingString:@"/"] stringByAppendingString:[Y2DeviceInfo getDeviceID]];
}

+(NSString*) getRegisterUrl
{
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/oauth/registration"];
}

+(NSString *) getUserCheckUrl
{
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/v2/open/oauth"];
}

+(NSString *) getUserBindingUrl
{
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/oauth/binding"];
}

+(NSString *) getPayUrl
{
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/payments"];
}

+(NSString *) getOrderCheckUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/pcheck"];
}

+(NSString *) getAppleOrderCheckUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/inPurchaseCheck"];
}

+(NSString *) getApplePromoOrderCheckUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/exchange/code"];
}

+(NSString *) getProtrolUrl
{
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/sdk/contract"];
}

+(NSString *) getPrivacyUrl
{
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/sdk/privacy"];
}

+(NSString *) getFindPasswordUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/password/find"];
}

+(NSString *) getProductUrl {
    return [[OpenSDK_DataManager getInstance].url stringByAppendingString:@"/open/product"];
}

+(NSString *) getSlideImageUrl {
    return [OpenSDK_DataManager getInstance].imgVerificationUrl;
}

+(NSString *) getDeviceID
{
    NSString *uuid=[[OpenSDK_LocalRecord getInstance] getLocalValueForKey:OpenSDK_L_KEYCHAIN_KEY];
    if(uuid==nil)
    {
        uuid = [[NSUUID UUID] UUIDString];
        [[OpenSDK_LocalRecord getInstance] saveData:OpenSDK_L_KEYCHAIN_KEY value:uuid];
    }
    
    return uuid;
}

+(NSString *) getTemporaryUserID {
    NSString *tUid=[[OpenSDK_LocalRecord getInstance] getLocalValueForKey:OpenSDK_L_TEMP_USERID];
    if(tUid==nil) {
        tUid=@"";
    }
    
    return tUid;
}

- (void)setUiStyle:(NSString *)uiStyle {
    _uiStyle = uiStyle;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (@available(iOS 13.0, *)) {
            UIWindow *window = [[UIApplication sharedApplication] keyWindow];
            if ([uiStyle isEqual:@"0"]) {
                window.overrideUserInterfaceStyle = UIUserInterfaceStyleUnspecified;
            } else if ([uiStyle isEqual:@"1"]) {
                window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
            } else if ([uiStyle isEqual:@"2"]) {
                window.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
            } else {
                window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
            }
        } else {
            // Fallback on earlier versions
        }
    });
}

+ (NSString *)getUIStyle {
    return  [OpenSDK_DataManager getInstance].uiStyle;
}

+(NSString *)getUserCenterUrl {
    return [OpenSDK_DataManager getInstance].userCenterUrl;
}

//获取本地的国家编码
-(NSDictionary *) getCountryCodeFromCurMachine {
    NSLocale *currentLocale = [NSLocale currentLocale];
    NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
    for( int i=0; i<_countryCodeInfo.count; i++) {
        if([[((NSMutableDictionary *)[_countryCodeInfo objectAtIndex:i]) objectForKey:OpenSDK_S_COUNTRY_CODE] isEqualToString:countryCode]) {
            if([[OpenSDK_LocalRecord getInstance] getLocalValueForKey:OpenSDK_L_COUNTRY_CODE]==nil) {
                [[OpenSDK_LocalRecord getInstance] saveData:OpenSDK_L_COUNTRY_CODE value:countryCode];
            }
            return ((NSMutableDictionary *)[_countryCodeInfo objectAtIndex:i]);
        }
    }
    if([_countryCodeInfo count]>0) {
        [[OpenSDK_LocalRecord getInstance] saveData:OpenSDK_L_COUNTRY_CODE value:[_countryCodeInfo[0] objectForKey:OpenSDK_S_COUNTRY_CODE]];
        return _countryCodeInfo[0];
    } else {
        return nil;
    }
}

#pragma mark - CurrentAccount 当前账号
static NSString * const KEY_CURRENT_ACCOUNT=@"OpenSDK_Current_Account";


- (void)setCurAccount:(OpenSDK_AccountRecord *)account {
    if (account == nil) {
        self.currentAccount = nil;
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:KEY_CURRENT_ACCOUNT];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } else {
        self.currentAccount = account;
        // 持久化到本地
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:account];
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:KEY_CURRENT_ACCOUNT];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (OpenSDK_AccountRecord *)getCurAccount {
    if (self.currentAccount == nil) {
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:KEY_CURRENT_ACCOUNT];
        if (data != nil) {
            self.currentAccount = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
    }
    return self.currentAccount;
}

#pragma mark -  预登录账号
static NSString * const KEY_PRE_LOGIN_ACCOUNT=@"OpenSDK_Pre_Login_Account";
- (void)setPreLoginAccount:(OpenSDK_AccountRecord *)account {
    if (account == nil) {
        _preLoginAccount = nil;
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:KEY_PRE_LOGIN_ACCOUNT];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } else {
        _preLoginAccount = account;
        // 持久化到本地
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:account];
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:KEY_PRE_LOGIN_ACCOUNT];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (OpenSDK_AccountRecord *)getPreLoginAccount {
    if (_preLoginAccount == nil) {
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:KEY_PRE_LOGIN_ACCOUNT];
        if (data != nil) {
            _preLoginAccount = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
    }
    return _preLoginAccount;
}

#pragma mark - historyAccount 账号历史记录
static NSString * const KEY_HISTORY_ACCOUNT=@"OpenSDK_History_Account";
- (void)addAccount:(OpenSDK_AccountRecord *) account {
    if (self.historyAccounts == nil) {
        // 从本地加载
        self.historyAccounts = [self loadAccounts];
    }
    [self.historyAccounts setObject:account forKey:account.openId];
    // 持久化到本地
    [self saveAccounts:self.historyAccounts];
}

- (void)removeAccount:(OpenSDK_AccountRecord *) account {
    if (self.historyAccounts != nil) {
        [self.historyAccounts removeObjectForKey: account.openId];
        // 持久化到本地
        [self saveAccounts:self.historyAccounts];
    }
}

- (void)removeAccountByOpenId:(NSString *) openId {
    if (self.historyAccounts != nil && openId != nil) {
        [self.historyAccounts removeObjectForKey:openId];
        // 持久化到本地
        [self saveAccounts:self.historyAccounts];
    }
}

- (NSArray *)getAccountList:(OpenSDK_AccountRecord *) account {
    if (self.historyAccounts == nil) {
        // 从本地加载
        self.historyAccounts = [self loadAccounts];
    }
    NSMutableDictionary *copyDic = [[NSMutableDictionary alloc] initWithDictionary:self.historyAccounts];
    if (account != nil) {
        [copyDic removeObjectForKey:account.openId];
    }
    NSArray *accounts = [copyDic allValues];
    //排序后，返回
    NSArray *result = [accounts sortedArrayUsingComparator:^NSComparisonResult(OpenSDK_AccountRecord * obj1, OpenSDK_AccountRecord * obj2) {
        return obj2.loginTime - obj1.loginTime;
    }];
    return result;
}

- (NSArray *)getAccountList {
    if (self.historyAccounts == nil) {
        // 从本地加载
        self.historyAccounts = [self loadAccounts];
    }
    NSMutableDictionary *copyDic = [[NSMutableDictionary alloc] initWithDictionary:self.historyAccounts];
    NSArray *accounts = [copyDic allValues];
    //排序后，返回
    NSArray *result = [accounts sortedArrayUsingComparator:^NSComparisonResult(OpenSDK_AccountRecord * obj1, OpenSDK_AccountRecord * obj2) {
        return obj2.loginTime - obj1.loginTime;
    }];
    return result;
}

#pragma mark - private 私有方法
// 从本地持久层加载
- (NSMutableDictionary *)loadAccounts {
    NSDictionary *localData = [[NSUserDefaults standardUserDefaults] dictionaryForKey:KEY_HISTORY_ACCOUNT];
    if (localData == nil) {
        return [[NSMutableDictionary alloc] init];
    }
    NSMutableDictionary *result =[[NSMutableDictionary alloc] init];
    for (NSString *key in localData) {
        OpenSDK_AccountRecord *account = [NSKeyedUnarchiver unarchiveObjectWithData:localData[key]];
        if (account != nil) {
            [result setObject:account forKey:key];
        }
    }
    return result;
}

// 持久化到本地
- (void)saveAccounts:(NSMutableDictionary *)accounts {
    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    for (NSString *key in accounts) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:accounts[key]];
        [result setObject:data forKey:key];
    }
    [[NSUserDefaults standardUserDefaults] setObject:result forKey:KEY_HISTORY_ACCOUNT];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
@end
